<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Medal class
 *
 * @category	Admin
 */
class MedalAction extends AdminAction
{

	protected $Medal;
	protected $MedalLog;


	//初始化
	public function _initialize()
	{
		parent::_initialize();
		$this->Medal = D('Medal');
		$this->MedalLog = D('MedalLog');
	}


	//勋章列表
	public function medalList()
	{
	    import('ORG.Util.Page');

		$total = $this->Medal->count();
		$Page  = new Page($total);
		$pagination = $Page->show();
		$medalList = $this->Medal->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->assign('pagination', $pagination);
		$this->assign('medalList', $medalList);
		$this->display();
	}


	//勋章管理
	public function manageMedal()
	{
	    if ($this->isPost())
		{
			/* ------------- 新增勋章 --------------*/
			$newName = $_POST['new_name'];
			$newDisplayOrder = $_POST['new_display_order'];
			$newDescription = $_POST['new_description'];
			$newImage = $_POST['new_image'];
			$newStatus = $_POST['new_status'];
			foreach ($newName as $key => $value)
			{
				if (!empty($newName[$key]) && !empty($newImage[$key]))
				{
					$data = array(
						'name'          => $newName[$key],
						'image'         => $newImage[$key],
						'description'   => $newDescription[$key],
						'display_order' => intval($newDisplayOrder[$key]),
						'status'        => intval($newStatus),
					);
					$this->Medal->add($data);
				}
			}
			/* ------------- 编辑已有勋章 -------------*/
			$mods = $_POST['mods'];
			$name = $_POST['name'];
			$displayOrder = $_POST['display_order'];
			$description = $_POST['description'];
			$image = $_POST['image'];
			$status = $_POST['status'];
			if (!empty($name))
			{
				foreach ($name as $key => $value)
				{
				    if (!empty($name[$key]) && !empty($image[$key]))
				    {
				        $data = array(
    						'name'          => $name[$key],
    						'image'         => $image[$key],
    						'display_order' => intval($displayOrder[$key]),
    						'status'        => intval($status[$key]),
    					);
    					$where = array('medal_id' => $key);
    					$this->Medal->where($where)->save($data);
    			    }
				}
			}
			/*--------------- 删除已有勋章 ----------------*/
			if (!empty($mods))
			{
				$where = array('medal_id' => array('in', $mods));
				$this->MedalLog->where($where)->delete();
				$this->Medal->where($where)->delete();
			}

			$this->Medal->cacheMedals();

			$this->success(L('medal.medal_updated_succeed'));
		}
	}


	//勋章编辑
	public function editMedal()
	{
		$medalID = intval($_REQUEST['medal_id']);
        $medalInfo = $this->Medal->find($medalID);

		if ($this->isPost())
		{
        	if (!$this->Medal->create())
        	{
				$this->error($this->Medal->getError());
			}

			if (2 == $_POST['award_type'] && empty($_POST['permission']))
			{
				$this->error(L('medal.exp_required'));
			}

			$exp = "/^(\'|\"|\+|\-|\*|\/|\.|>|<|=|\d|\s|point_count|question_count|answer_count|comment_count|best_answer_count|follower_count|register_date|and|or)+$/";
            if (!empty($_POST['permission']) && !preg_match($exp, Input::getVar($_POST['permission'])))
            {
                $this->error(L('medal.exp_invalid'));
		    }

			$data = array(
				'name'        => $_POST['name'],
				'image'       => $_POST['image'],
				'description' => $_POST['description'],
				'expiration'  => intval($_POST['expiration']),
				'award_type'  => intval($_POST['award_type']),
				'permission'  => $_POST['permission'],
			);
			$map = array('medal_id' => $medalID);
			$this->Medal->where($map)->save($data);

			$this->Medal->cacheMedals();

			$this->success(L('medal.medal_edited_succeed'));
		}
		else
		{
			$medalAwardTypeRadios = array(
			    1 => L('medal.award_by_admin'),
			    2 => L('medal.award_by_application'),
			);
			$medalAwardTypeChecked = !empty($medalInfo['award_type']) ? $medalInfo['award_type'] : 1;
			$this->assign('medalAwardTypeRadios', $medalAwardTypeRadios);
			$this->assign('medalAwardTypeChecked', $medalAwardTypeChecked);

			$this->assign('rs', $medalInfo);
			$this->display();
		}
	}


	//勋章审核
	public function approveMedal()
	{
	    $prefix = C('DB_PREFIX');

		if ($this->isPost())
		{
			if (empty($_POST['mods']))
			{
                $this->redirect('Admin-Medal/approveMedal');
			}

            $medals = F('cache_medals');
			$mods = implode(',', $_POST['mods']);

			$sql  = " SELECT log.*, u.medal ";
		    $sql .= " FROM {$prefix}medal_log AS log ";
		    $sql .= " LEFT JOIN {$prefix}user AS u USING(user_id) ";
		    $sql .= " WHERE log_id IN ({$mods})";

		    $results = $this->Medal->query($sql);

		    if (isset($_POST['action']['approve']))
			{
                foreach ($results as $value)
                {
                    $tmpMedals = explode(',', $value['medal']);
                    $newMedals[] = $value['medal_id'];
                    $expiration = $medals[$value['medal_id']]['expiration'];

                    $map = array('log_id' => $value['log_id']);
                    $data = array(
                        'expire_time' => $expiration ? time() + $expiration * 86400 : 0,
                        'type'        => 2,
                        'status'      => $expiration ? 1 : 0,
                    );
                    $this->MedalLog->where($map)->save($data);

                    $myMedals = array_unique(array_merge($tmpMedals, $newMedals));
                    $map = array('user_id' => $value['user_id']);
                    $myMedals = trim(implode(',', $myMedals), ',');
                    $this->_User->where($map)->setField('medal', $myMedals);
                }
                $message = L('medal.medal_approved_succeed');
			}
			elseif (isset($_POST['action']['disapprove']))
			{
			    $map = array('log_id' => array('in', $mods));
                $this->MedalLog->where($map)->setField('type', -1);
                $message = L('medal.medal_disapproved_succeed');
			}
			$this->success($message);
		}
		else
		{
		    $sql  = " SELECT log.*, m.name, m.image, u.username, u.medal ";
		    $sql .= " FROM {$prefix}medal_log AS log ";
		    $sql .= " LEFT JOIN {$prefix}medal AS m ON log.medal_id=m.medal_id ";
		    $sql .= " LEFT JOIN {$prefix}user AS u ON log.user_id=u.user_id ";
		    $sql .= " WHERE log.type=0 ORDER BY log.create_time DESC ";

		    $applyList = $this->Medal->query($sql);

			$this->assign('applyList', $applyList);
			$this->display();
		}
	}


	//用户勋章
	public function userMedal()
	{

		$Medal = D('Medal');
		$MedalLog = D('MedalLog');
		
        $medals = F('cache_medals');
        $userID = intval($_REQUEST['user_id']);
        $user = $this->_User->find($userID);

		if ($this->isPost())
		{
		    foreach ($_POST['medals'] as $value)
		    {
		        $expiration = $medals[$value]['expiration'];
		        $map = array(
		           'user_id'  => $userID,
		           'medal_id' => $value,
		        );
		        $result = $MedalLog->where($map)->find();
		        if (empty($result) || !in_array($value, explode(',', $user['medals'])))
		        {
		            $data = array(
    		           'user_id'     => $user['user_id'],
    		           'medal_id'    => $value,
    		           'create_time' => time(),
    		           'expiration'  => $expiration ? time() + $expiration * 86400 : 0,
    		           'type'        => 1,
    		           'status'      => $expiration ? 1 : 0,
    		        );
    		        $MedalLog->add($data);
		        }
		    }

			$map = array('user_id' => $userID);
			$this->_User->where($map)->setField('medals', implode(',', $_POST['medals']));
			$this->success(L('medal.user_medal_updated_succeed'));
		}
		else
		{
			$medalList = $Medal->select();
			$this->assign('user', $user);
			$this->assign('medalList', $medalList);
			$this->display();
		}
	}

}
// End  Class

/* End of file MedalAction.class.php */
/* Location: ./App/Lib/Action/Admin/MedalAction.class.php */
